import { DeleteOutlined } from '@ant-design/icons';
import {Button, message, Popconfirm, Tag} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { queryLog, deleteLog } from './service';
import type { LogItem, TableListPagination } from './data';

/**
 * 批量删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: LogItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    const res = await deleteLog({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: LogItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteLog({
      key: [record.id],
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<LogItem[]>([]);

  // 表头，列表渲染设置
  // @ts-ignore
  const columns: ProColumns<LogItem>[] = [
    // 关键字搜索
    {
      title: 'keyword',
      hideInTable: true,
      hideInForm: false,
      dataIndex: 'keyword',
      formItemProps: { label: '关键字' },
    },
    // 列表字段
    {
      title: 'ID',
      // copyable: true,  // 展示复制按钮
      dataIndex: 'id', // 数据索引
      width: 60,
      // ellipsis: true,  // 超长度自动收缩
      // tip: 'ID',    // 提示文字tip
      sorter: (a, b) => a.id - b.id, // 开启排序
      search: false, // 是否在header展示此搜索框
      hideInTable: false, // 不在表格中展示
      hideInSearch: true, // 不在搜索框中展示
      editable: false,
    },
    {
      title: '对象',
      width: 120,
      dataIndex: 'username',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '类型',
      width: 60,
      dataIndex: 'level',
      valueEnum: {
        "info": { text: '信息', status: 'Processing' },
        "warn": { text: '警告', status: 'Warning' },
        "error": { text: '错误', status: 'Error' },
      },
      align: 'center',
      render: (_,record) => {
        if (record.level === "info"){
          return <Tag color={"blue"}>信息</Tag>
        }else if (record.level === "warn"){
          return <Tag color={"yellow"}>警告</Tag>
        }else {
          return <Tag color={"red"}>错误</Tag>
        }
      }
    },
    {
      title: '记录时间',
      width: 150,
      dataIndex: 'createTime',
      hideInSearch: true,
      valueType: 'dateTime',
      align: 'center',
      sorter: (a, b) => {
        // 开启排序
        // 时间的排序，需要先转存时间戳
          const aTime = new Date(a.createTime).getTime();
        const bTime = new Date(b.createTime).getTime();
        return aTime - bTime;
      },
    },
    {
      title: '日志',
      dataIndex: 'content',
      valueType: 'textarea',
      hideInSearch: true,
      copyable: true,
      ellipsis: true
    },
    {
      title: '操作',
      key: 'option',
      width: 65,
      align: 'right',
      valueType: 'option',
      render: (text, record) => [
        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
          const success = await handleSingleRemove(record);
          if (success) {
            actionRef?.current?.reload();
          }
        }}>
          <a style={{color: "red"}} ><DeleteOutlined /> 删除</a>
        </Popconfirm>
      ],
    },
  ];

  // @ts-ignore
  return (
    <PageContainer pageHeaderRender={false}>
      <ProTable<LogItem, TableListPagination>
        headerTitle="日志列表"
        actionRef={actionRef}
        rowKey="id"
        // 设置分页参数
        pagination={{ defaultPageSize: 10, showSizeChanger: true }}

        // 表格数据源
        request={queryLog}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              行 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
